package com.tianyadu.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @FileName: TokenFilter
 * @Description: token过滤拦截，若token为空，则返回401
 * @author: xueyj
 * @create: 2018-11-26 18:04
 */
@Component
public class TokenFilter extends ZuulFilter{

    /**
      * @Description: 拦截类型：pre
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/26 18:06
      */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
      * @Description: 拦截级别
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/26 18:07
      */
    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    /**
      * @Description: 是否开启过滤
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/26 18:07
      */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
      * @Description: 拦截信息校验
      * @param:
      * @return:
      * @author:
      * @date:   2018/11/26 18:07
      */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //这里从url参数里获取, 也可以从cookie, header里获取
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}